<template>
  <div class="SQLDefine">
    <div v-show="!dialogVisible">
      <el-form
        style="background-color: #efeeef; padding: 10px"
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="数据源">
          <el-select
            v-model="selectValue"
            @change="selectChange"
            placeholder="请选择数据连接池"
          >
            <el-option
              v-for="item in datasource"
              :key="item.id"
              :label="item.datasourceName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-card class="container" style="height: 100%">
        <el-row>
          <el-col :span="6" style="margin-right: 10px">
            <div
              class="grid-content bg-purple"
              style="
                border: 1px solid #dfe4ed;
                text-align: center;
                height: 710px;
              "
            >
              <el-input
                clearable
                size="small"
                style="width: 95%; margin: 10px"
                placeholder="输入关键字搜索库表"
              ><i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="getTableAliasList"
              ></i>
              </el-input>
              <el-table
                highlight-current-row
                height="290"
                :data="tableData"
                style="width: 100%; margin-bottom: 10px"
                @current-change="handleCurrentChange"
              >
                <el-table-column
                  prop="tableName"
                  label="名称"
                ></el-table-column>
                <el-table-column prop="tableNameAlias" label="别名">
                </el-table-column>
              </el-table>
              <el-row>
                <el-table
                  v-show="showColTable"
                  :data="colList"
                  height="356"
                  highlight-current-row
                  @current-change="handleColTable"
                  row-key="id"
                  border
                >
                  <el-table-column
                    prop="columnName"
                    label="字段名"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <!-- <el-table-column prop="dataType" label="数据类型" :show-overflow-tooltip="true"></el-table-column> -->
                  <el-table-column
                    prop="columnAlias"
                    label="字段别名"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <!-- <el-table-column prop="columnDesc" label="字段说明" :show-overflow-tooltip="true"></el-table-column> -->
                </el-table>
              </el-row>
            </div>
          </el-col>
          <el-col :span="17" style="height: 100%; position: relative">
            <div style="position: absolute; top: 0; right: 0; z-index: 99">
              <el-checkbox v-model="executeParams.isPage" label="number" @change="checkboxChange" true-label=1 false-label=0>是否开启分页</el-checkbox>
              <el-button type="primary" @click.native="formatSql"
              >美化SQL
              </el-button>
              <el-button type="primary" @click.native="getSqlData"
              >执行SQL
              </el-button>
            </div>
            <div class="grid-content bg-purple-light" style="height: 100%">
              <el-tabs v-loading="loading" v-model="activeName" type="card">
                <el-tab-pane label="查询语句" name="first">
                  <el-row>
                    <div style="padding: 20px">
                      <el-form ref="form" :model="SQLform" label-width="80px">
                        <el-form-item style="text-align: center">
                          <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 100 }"
                            style="width: 100%; margin: 0 -10px 20px -100px"
                            placeholder="请输入SQL语句"
                            @change="sendSQL"
                            v-model="SQLform.sentence"
                          ></el-input>

                          <!-- <el-button type="primary" @click="addSqlQuota"
                        >新增指标
                        </el-button> -->
                        </el-form-item>
                      </el-form>
                      <!-- :header-cell-style="{color:'#1086b3',cursor: 'pointer','text-decoration': 'underline'}" -->
                      <el-table
                        :data="SQLData"
                        height="300"
                        row-key="id"
                        border
                        @header-click="headerClick"
                      >
                        <el-table-column
                          v-for="(value,key,index) in sqlLabel"
                          :show-overflow-tooltip="true"
                          :key="index"
                          :prop="key"
                          :label="key"
                          align="center"
                        >
                        </el-table-column>
                      </el-table>
                    </div>

                  </el-row>
                </el-tab-pane>
              </el-tabs>

            </div>
            <el-row style="margin-top: 20px">
              <el-button @click="nextStep" type="primary"
              >下一步
              </el-button>
              <pagination
                v-show="executeParams.isPage==1&&resultCount>0"
                :page-sizes="[5, 50, 100]"
                :page-size="5"
                :total="resultCount"
                :page.sync="executeParams.pageNum"
                :limit.sync="executeParams.pageSize"
                @pagination="getSqlData"
              />
            </el-row>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <div v-show="dialogVisible">
      <custom-quota
        :showBtn="showBtn"
        :quota-create-type="4"
        :prop-measure-col="measureCol"
        :sql="SQLform.sentence"
        :datasourceId="queryParams.datasourceId"
        @backStep="backStep"
      ></custom-quota>
    </div>
  </div>
</template>
<script>
  //存在类库表定义指标功能 暂时屏蔽了
  import { getColAlias, getDatasource, getTableAliasEnable, queryComputeType } from '@/api/quota/define/define.js'
  import { executeSql } from '@/api/quota/sqlQuota/sqlQuota'
  import { listColAlias } from '@/api/metadata/colalias'
  import CustomQuota from '@/views/quota/custom_quota/index.vue'
  import sqlFormatter from 'sql-formatter'

  export default {
    components: { CustomQuota },
    data() {
      return {
        loading: false,
        showBtn: true,
        dialogVisible: false,
        checkList: [],
        //指标值类型
        typeId: '0',
        //计算类型
        computedType: [],
        //测试结果table显示
        showColTable: false,
        //SQL语句查询结果
        SQLData: [],
        sqlLabel: [],
        colList: [],
        //SQL语句
        SQLform: {
          sentence: 'SELECT * FROM'
        },
        measureCol: '',
        SqueryParams: {
          pageNum: 1,
          pageSize: 10,
          orderField: 'UPDATE_DATE',
          order: 'desc',
          tablenameAliasId: ''
        },
        routeData: {
          quota: [],
          dimension: [],
          themeId: this.themeId
        },
        //字段弹窗数据
        fieldData: [],
        multipleSelection: [],
        dialogTableVisible: false,
        dialogFormVisible: false,
        dataBaseList: [],
        confirmSlot: undefined,
        selectValue: '',
        datasource: [],
        tableData: [],
        resultCount: 0,
        executeParams: {
          isPage: 0,
          pageNum: 1,
          pageSize: 5
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderField: 'UPDATE_DATE',
          order: 'desc',
          datasourceId: undefined,
          keyword: undefined
        },
        activeName: 'first'
      }
    },
    created() {
      this.getDatasourceList()
      //获取计算类型
      queryComputeType().then((res) => {
        this.computedType = res.data
      })
    },
    methods: {
      checkboxChange(val){
        if(val==0){
          this.executeParams.pageNum=1
          this.executeParams.pageSize=5
        }
      },
      headerClick(column, event) {
        if ('NUMBER' !== this.sqlLabel[column.label]) {
          this.$message({
            type: 'warning',
            message: '该列不可为度量列'
          })
          return
        }
        this.measureCol = column.label
      },
      //向父组件传递sql语句
      sendSQL() {
        this.$emit('getSQL', this.SQLform.sentence)
      },
      //下一步
      nextStep() {
        this.addSqlQuota()
      },
      backStep() {
        this.dialogVisible = false
      },
      //处理dialog是否打开
      addSqlQuota() {
        // if (this.measureCol === '') {
        //   this.$message({
        //     type: 'warning',
        //     message: '未选择度量列'
        //   })
        //   return
        // }
        if (this.queryParams.datasourceId == undefined) {
          this.$message({
            type: 'warning',
            message: '请先选择数据源'
          })
          return
        }
        this.SQLform.sentence = this.SQLform.sentence.toUpperCase()
        if (this.SQLform.sentence == '' || this.SQLform.sentence == 'SELECT * FROM') {
          this.$message({
            type: 'warning',
            message: 'SQL非法'
          })
          return
        }
        this.dialogVisible = true
      },
      handleColTable(val) {
        this.SQLform.sentence = this.SQLform.sentence.toUpperCase()

        let beginIndex = this.SQLform.sentence.lastIndexOf('select') + 6
        let endIndex = this.SQLform.sentence.indexOf('FROM')
        if (beginIndex !== -1 && endIndex !== -1) {
          let str = this.SQLform.sentence.substring(beginIndex, endIndex)
          this.SQLform.sentence = this.SQLform.sentence.replace(
            str,
            str + ',' + val.columnName + ' '
          )
        }
        let first1 = this.SQLform.sentence.indexOf('*')
        let first2 = this.SQLform.sentence.indexOf(',') + 1
        if (first1 !== -1 && first2 !== -1) {
          let replace = this.SQLform.sentence.substring(first1, first2)
          this.SQLform.sentence = this.SQLform.sentence.replace(replace, '')
        }
      },
      //格式化sql
      formatSql() {
        this.SQLform.sentence = sqlFormatter.format(this.SQLform.sentence)
      },
      //获取测试结果
      getSqlData() {
        if (this.queryParams.datasourceId == undefined) {
          this.msgError('请先选择数据源')
          return
        }
        this.SQLform.sentence = this.SQLform.sentence.toUpperCase()
        if (
          this.SQLform.sentence == 'SELECT * FROM' ||
          this.SQLform.sentence == ''
        ) {
          this.msgError('非法SQL')
          return
        }
        this.loading = true
        this.executeParams.datasourceId = this.queryParams.datasourceId
        this.executeParams.sql = this.SQLform.sentence
        executeSql(this.executeParams).then((res) => {
          this.sqlLabel = res.data.label
          this.SQLData = res.data.data
          this.resultCount = res.data.count
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      getColList() {
        let query = {
          current: 1,
          size: 100,
          tablenameAliasId: this.SqueryParams.tablenameAliasId
        }
        listColAlias(query).then((response) => {
          this.colList = response.data.records
          if (this.colList.length <= 0) {
            this.$message({
              type: 'warning',
              message: '暂无字段数据'
            })
          } else {
            this.showColTable = true
          }
        })
      },
      //提交选中字段
      submitSelectValue() {
      },
      //选中字段
      handleSelectionChange() {
      },
      //选择字段
      selectField(val) {
        this.dialogTableVisible = true
        this.queryParams.tablenameAliasId = val.id
        getColAlias(this.queryParams).then((res) => {
          this.fieldData = res.data
        })
      },
      //选中数据库表
      handleCurrentChange(val) {
        if (!val) {
          return
        }
        this.executeParams.isPage = 0
        this.dataBaseList.push(val)
        //查询字段 处理sql
        this.SQLform.sentence = this.SQLform.sentence.toUpperCase()
        let table = this.SQLform.sentence.match(/\s+FROM\s+(\w+)/g)
        console.log(table)
        if (table != null) {
          this.SQLform.sentence = this.SQLform.sentence.replace(
            table,
            ' FROM ' + val.tableName
          )
        } else {
          let index = this.SQLform.sentence.indexOf('FROM')
          if (index !== -1) {
            this.SQLform.sentence = this.SQLform.sentence.replace(
              'FROM',
              ' FROM ' + val.tableName
            )
          }
        }

        this.SqueryParams.tablenameAliasId = val.id
        this.getColList()
      },
      //选中的值
      selectChange(val) {
        this.executeParams.isPage = 0
        this.queryParams.datasourceId = val
        this.getTableAliasList()
        this.$emit('getDatasourceId', val)
      },
      //加载表别名数据
      getTableAliasList() {
        if (this.queryParams.datasourceId == undefined) {
          this.msgError('请先选择数据源')
        } else {
          getTableAliasEnable(this.queryParams).then((res) => {
            this.tableData = res.data
          })
        }
      },
      //加载数据源数据
      getDatasourceList() {
        getDatasource().then((res) => {
          this.datasource = res.data
        })
      },
      onSubmit() {
        console.log('submit!')
      }
    }
  }
</script>
<style lang="less">

  .el-form-item {
    margin-bottom: 0;
  }

  .SQLDefine {
    .el-tabs__header {
      margin: 0;
    }

    .el-textarea textarea {
      min-height: 150px !important;
    }

    // .el-tabs__content {
    //   height: 100% !important;
    // }

    .el-tag {
      display: inline-block;
    }

    .dbtable {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 150px;
      height: 60px;
      background-color: #cbeaff;
      border-radius: 5px;
      text-align: center;
      padding-top: 10px;
    }

    .el-tabs {
      height: 539px;
    }

    .el-tabs__content {
      border: 1px solid #dfe4ed;
      height: 94%;
    }
  }
</style>
